package ro.ubbcluj.cs.damate.managers.management;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import ro.ubbcluj.cs.damate.managers.BaseView;
import ro.ubbcluj.cs.damate.persistence.entities.Section;
import ro.ubbcluj.cs.damate.persistence.entities.Task;
import ro.ubbcluj.cs.damate.services.SectionService;
import ro.ubbcluj.cs.damate.services.TaskService;

import java.io.Serializable;
import java.util.List;

/**
 * @author Lorand Fazakas
 */
@Component
@Scope("view")
public class TaskManager extends BaseView implements Serializable {

    @Autowired
    private ManagerView managerView;

    @Autowired
    private TaskService taskService;

    @Autowired
    private SectionService sectionService;

    private Task newOrModifiedTaskBean;

    private List<Task> tasks;
    private List<Task> filteredTasks;

    public void save() {
        Section selectedSection = sectionService.findById(newOrModifiedTaskBean.getSection().getSectionId());
        newOrModifiedTaskBean.setSection(selectedSection);
        taskService.create(newOrModifiedTaskBean);
        clean();
        managerView.switchPanel(ManagerView.ManagerPanel.LIST_TASKS.name());
    }

    public void edit(Task task) {
        setNewOrModifiedTaskBean(task);
        managerView.switchPanel(ManagerView.ManagerPanel.NEW_TASK.name());
    }

    public void addTask(Section section) {
        getNewOrModifiedTaskBean().setSection(section);
        managerView.switchPanel(ManagerView.ManagerPanel.NEW_TASK.name());
    }

    public void delete(Task task) {
        taskService.delete(task);
        clean();
    }

    private void clean() {
        this.newOrModifiedTaskBean = null;
        this.tasks = null;
        this.filteredTasks = null;
    }

    public void openPanel(String panelName) {
        clean();
        managerView.switchPanel(panelName);
    }

    public Task getNewOrModifiedTaskBean() {
        if (newOrModifiedTaskBean == null) {
            this.newOrModifiedTaskBean = new Task();
            newOrModifiedTaskBean.setSection(new Section());
        }
        return newOrModifiedTaskBean;
    }

    public void setNewOrModifiedTaskBean(Task newOrModifiedTaskBean) {
        this.newOrModifiedTaskBean = newOrModifiedTaskBean;
    }

    public List<Task> getTasks() {
        if (tasks == null) {
            this.tasks = taskService.findAll();
        }
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }

    public List<Task> getFilteredTasks() {
        return filteredTasks;
    }

    public void setFilteredTasks(List<Task> filteredTasks) {
        this.filteredTasks = filteredTasks;
    }

    public List<Section> getAvailableSections() {
        return sectionService.findAll();
    }
}